package com.greenline.search.report.util;

import com.greenline.search.report.model.Configuration;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: liulei
 * Date: 14-2-12
 * Time: 下午2:42
 * To change this template use File | Settings | File Templates.
 */
public class EmailUtils {

    public static void main(String args[]) {
        String timeLine = "20140210-20140216";
        String content = "<h1>A test email for search data weekly report.</h1> hello.";
        EmailUtils.sendEmail(timeLine,content);
    }

    public static void sendEmail(String timeLine,String content){
        SendInfo info = new SendInfo();
        info.setUserName("liulei@guahao.com");
        info.setPassword("19880726");
        info.setPort("25");
        info.setHost("mail.guahao.com");
        info.setAddressor("liulei@guahao.com");
        if(Configuration.FLAG_TEST){
            info.setRecipients("liulei@guahao.com");
        }else {
            info.setRecipients("search@guahao.com");
            info.setCcRecipients(new String[]{"huhx@guahao.com","qingyt@guahao.com"});
        }
        info.setSubject(timeLine);
        info.setContent(content);
        info.setValidate(true);
        info.setShowName("刘磊");
        Properties properties = info.getProperties();
        try {
            SimpleMailSender sender = new SimpleMailSender();
            sender.sendTextMail(info, properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


/**
 * 发送信息的相关配置
 * @author tdw
 *
 */
class SimpleMailSender {

    public boolean sendTextMail(SendInfo info, Properties properties)
            throws MessagingException, UnsupportedEncodingException {
        boolean ifSuccess = false;
        Authenticator authenticator = new MyAuthenticator(info.getUserName(),
                info.getPassword());
        Session session = Session.getInstance(properties, authenticator);
        MimeMessage message = new MimeMessage(session);
        message.setSubject(info.getSubject());
        message.setContent(info.getContent(), "text/html;charset=gb2312");
        message.setSentDate(new Date()); // 设置邮件发送日期
        Address address = new InternetAddress(info.getAddressor(),
                info.getShowName());
        message.setFrom(address); // 设置邮件发送者的地址
        Address toAddress = new InternetAddress(info.getRecipients()); // 设置邮件接收方的地址
        message.addRecipient(Message.RecipientType.TO, toAddress);

        String[] ccAddressString = info.getCcRecipients();
        if(ccAddressString != null){
            Address[] ccAddress = new Address[ccAddressString.length];
            for(int i = 0; i < ccAddressString.length; i++){
                ccAddress[i] = new InternetAddress(ccAddressString[i]);
            }
            message.setRecipients(Message.RecipientType.CC, ccAddress);
        }

        Transport.send(message); // 发送邮件
        ifSuccess = true;
        System.out.println("send success!");
        return ifSuccess;
    }
}


/**
 * 必须继承 javax.mail.Authenticator.
 * @author tdw
 *
 */
class MyAuthenticator extends Authenticator {
    String userName;
    String password;

    public MyAuthenticator(String userName, String password) {
        super();
        this.userName = userName;
        this.password = password;
    }

    public MyAuthenticator() {

    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
}


/**
 * model
 * @author tdw
 *
 */
class SendInfo implements Serializable {

    private static final long serialVersionUID = -7790647664818201443L;
    // 邮箱用户
    private String userName;
    // 密码
    private String password;
    // 发件人
    private String addressor;
    // 收件人
    private String recipients;
    // 服务主机
    private String host;
    // 端口号
    private String port;
    // 是否验证身份（免费邮都需要）
    private boolean validate = true;
    // 发件人显示名称
    private String showName;
    // 主题
    private String subject;
    // 发送内容
    private String content;
    //抄送人
    private String[] ccRecipients;

    String[] getCcRecipients() {
        return ccRecipients;
    }

    void setCcRecipients(String[] ccRecipients) {
        this.ccRecipients = ccRecipients;
    }

    public String getShowName() {
        return showName;
    }

    public void setShowName(String showName) {
        this.showName = showName;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddressor() {
        return addressor;
    }

    public void setAddressor(String addressor) {
        this.addressor = addressor;
    }

    public String getRecipients() {
        return recipients;
    }

    public void setRecipients(String recipients) {
        this.recipients = recipients;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Properties getProperties() {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", this.host);
        properties.put("mail.smtp.port", this.port);
        properties.put("mail.smtp.auth", validate ? "true" : "false");
        return properties;
    }
}
